<template>
  <div class="index">
    <div class="footer"></div>
    <p>年龄分布</p>
    <div class="leftBotEchart"></div>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { getAgeData } from "@/api/echarts";
import { ref, onMounted } from "vue";
// 引入 Echarts
import * as echarts from "echarts";
import { useRouter } from "vue-router";
const router = useRouter();

const ageInfo = ref([]);

onMounted(() => {
  getData();
});
/**
 * 请求数据
 */
const getData = async () => {
  let res = await getAgeData();
  if (res.code == 0) {
    const {
      data: { ageTxt, ageNum },
    } = res;
    ageInfo.value = ageTxt.map((item, index) => {
      return {
        value: ageNum[index],
        name: item,
      };
    });
    initEcharts();
  } else if (res.msg.includes("登录")) {
    router.replace("/");
  }
};
/**
 * 初始化图表
 */
function initEcharts() {
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.querySelector(".leftBotEchart"));
  // 绘制图表
  myChart.setOption({
    tooltip: {
      trigger: "item",
    },
    legend: {
      y: "88%",
      left: "center",
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        color: "rgba(255, 255, 255, 0.5)",
        fontSize: 12, //字体大小
      },
    },
    series: [
      {
        name: "年龄分布",
        type: "pie",
        radius: ["30%", "60%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        // 中间的文字
        emphasis: {
          label: {
            show: true,
            fontSize: "20",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: ageInfo.value,
      },
    ],
  });
  // 图表跟随浏览器自适应
  window.addEventListener("resize", function () {
    myChart.resize();
  });
}
</script>

<style lang="scss" scoped>
.index {
  position: relative;
  p {
    width: 100%;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 8px;
    left: 0;
  }
  .leftBotEchart {
    width: 100%;
    height: 100%;
  }
  // 使用伪元素做边框
  .footer {
    &::before {
      content: "";
      width: 15px;
      height: 15px;
      border-bottom: 1px solid #02a6b5;
      border-left: 1px solid #02a6b5;
      position: absolute;
      bottom: 0;
      left: 0;
    }
    &::after {
      content: "";
      width: 15px;
      height: 15px;
      border-bottom: 1px solid #02a6b5;
      border-right: 1px solid #02a6b5;
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }
}
</style>
